﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;

namespace Xms.Abp.Messaging.Emailing;

public class SmtpTemplateEmailSenderProvider : TemplateEmailSenderProviderBase, ITemplateEmailSenderProvider, ITransientDependency
{
    public override string ProviderName => ITemplateEmailSenderProvider.Smtp;

    public SmtpTemplateEmailSenderProvider(EmailSettings emailSettings) : base(emailSettings)
    {
    }
    public override async Task SendEmailAsync(EmailMessage emailMessage, CancellationToken stoppingToken = default)
    {
        var mail = new MailMessage
        {
            To = { },
            CC = { },
            Subject = emailMessage.Subject,
            Body = emailMessage.Body,
            IsBodyHtml = emailMessage.IsBodyHtml
        };
        if (emailMessage.From.IsNullOrEmpty())
        {
            mail.From = new MailAddress(EmailSettings.DefaultFromAddress, EmailSettings.DefaultFromDisplayName);
        }
        else
        {
            mail.From = new MailAddress(emailMessage.From);
        }
        foreach (var to in emailMessage.Tos)
        {
            mail.To.Add(to);
        }
        foreach (var cc in emailMessage.CCs)
        {
            mail.CC.Add(cc);
        }
        using var smtpClient = new SmtpClient(EmailSettings.SmtpHost, EmailSettings.SmtpPort);
        smtpClient.EnableSsl = EmailSettings.SmtpEnableSsl;
        smtpClient.UseDefaultCredentials = EmailSettings.SmtpUseDefaultCredentials;
        if (!smtpClient.UseDefaultCredentials)
        {
            var userName = EmailSettings.SmtpUserName;
            if (!userName.IsNullOrEmpty())
            {
                var password = EmailSettings.SmtpPassword;
                var domain = EmailSettings.SmtpDomain;
                smtpClient.Credentials = !domain.IsNullOrEmpty()
                    ? new NetworkCredential(userName, password, domain)
                    : new NetworkCredential(userName, password);
            }
        }
        await smtpClient.SendMailAsync(mail);

    }
}
